package org.csu.jpetstore.controller;

import org.csu.jpetstore.bo.CartItemBO;
import org.csu.jpetstore.bo.LineItemBO;
import org.csu.jpetstore.bo.OrderBO;
import org.csu.jpetstore.common.CommonResponse;
import org.csu.jpetstore.common.OrderStatusCode;
import org.csu.jpetstore.common.ResponseCode;
import org.csu.jpetstore.service.CartService;
import org.csu.jpetstore.service.OrderService;
import org.csu.jpetstore.service.TokenService;
import org.csu.jpetstore.util.MyToken;
import org.csu.jpetstore.vo.LineItemVO;
import org.csu.jpetstore.vo.OrderFormVO;
import org.csu.jpetstore.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;


/**
 * @author huangzhangyan
 */
@Controller
@RequestMapping(value = "/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private CartService cartService;

    /**
     * 获取用户订单表单 List
     *
     * @param token    token
     * @param username 用户名
     * @return CommonResponse 用户订单表单的列表
     * @author huangzhangyan
     * @date 2022/4/24 14:18
     */
    @RequestMapping(value = "/accounts/{username}/orders", method = RequestMethod.GET)
    @ResponseBody
    public CommonResponse<List<OrderFormVO>> getOrderListByUsername(
            @RequestHeader("Authorization") MyToken token,
            @PathVariable String username) {

        // Token校验
        if (!tokenService.isUserIdEqualToken(username, token)) {
            return CommonResponse.createForError("Token校验失败,请重新登录");
        }

        // 获取用户的订单List
        List<OrderFormVO> orderFormVOList = new ArrayList<>();
        List<OrderBO> orderBOList = orderService.getOrderBOListByUsername(username);
        for (OrderBO orderBO : orderBOList) {
            orderFormVOList.add(OrderBO.toOrderFormVO(orderBO));
        }
        return CommonResponse.createForSuccess(orderFormVOList);
    }

    /**
     * 提交订单 提交的商品为购物车中所有商品
     * 前端返回的数据组合成OrderFormVO 只有个人信息 要计算总价,生成OrderId,当前Date
     *
     * @param token             token
     * @param username          用户名
     * @param shipProvince      收货地址的省
     * @param shipCity          收货地址的市
     * @param shipCounty        收货地址的县
     * @param shipDetailAddress 收货地址的详细地址
     * @param shipToFirstname   收货地址的姓
     * @param shipToLastname    收货地址的名
     * @author huangzhangyan
     * @date 2022/4/24 14:02
     */
    @RequestMapping(value = "/accounts/{username}/order", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<OrderVO> submitOrder(
            @RequestHeader("Authorization") MyToken token,
            @PathVariable String username,
            @RequestParam(name = "shipProvince") String shipProvince,
            @RequestParam(name = "shipCity") String shipCity,
            @RequestParam(name = "shipCounty") String shipCounty,
            @RequestParam(name = "shipDetailAddress") String shipDetailAddress,
            @RequestParam(name = "shipToFirstname") String shipToFirstname,
            @RequestParam(name = "shipToLastname") String shipToLastname
    ) {
        // 非空判断
        if (null == username || "".equals(username)) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数错误,用户名不能为空");
        }
        // Token校验
        if (!tokenService.isUserIdEqualToken(username, token)) {
            return CommonResponse.createForError("Token校验失败,请重新登录");
        }

        OrderFormVO orderSubmit = new OrderFormVO(username, shipProvince, shipCity, shipCounty, shipDetailAddress, shipToFirstname, shipToLastname);

        // 获取购物车中商品转LineItemVO
        List<LineItemVO> lineItemVOList = new ArrayList<>();
        List<CartItemBO> cartItemBOList = cartService.getCartByUsername(username).getCartItemBOList();
        for (int i = 0; i < cartItemBOList.size(); i++) {
            CartItemBO cartItemBO = cartItemBOList.get(i);

            LineItemVO lineItemVO = new LineItemVO();
            lineItemVO.setLineNumber(i);
            lineItemVO.setItemId(cartItemBO.getItemBO().getItemId());
            lineItemVO.setQuantity(cartItemBO.getQuantity());
            lineItemVO.setListPrice(cartItemBO.getItemBO().getListPrice());
            lineItemVO.setTimeStamp(new Date(System.currentTimeMillis()));
            lineItemVO.setStatus(OrderStatusCode.WAIT_PAYMENT.getDescription());

            lineItemVOList.add(lineItemVO);
        }

        OrderBO orderBO = OrderBO.toOrderBO(orderSubmit, lineItemVOList);
        orderService.insertOrder(orderBO);

        OrderVO orderVO = OrderBO.toOrderVO(orderBO);
        return CommonResponse.createForSuccess(orderVO);
    }

    /**
     * 用户查看自己订单的商品内容
     * 根据orderId查找
     *
     * @param token    token
     * @param username 用户名
     * @param orderId  订单号
     * @return CommonResponse
     * @author CSU_Luoyuhang
     * @date 2022/4/13 19:58
     */
    @RequestMapping(value = "/accounts/{username}/orders/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResponse<List<LineItemVO>> getLineItemVOListByOrderId(
            @RequestHeader("Authorization") MyToken token,
            @PathVariable("orderId") int orderId,
            @PathVariable String username) {
        // 非空判断
        if (null == username || "".equals(username)) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数错误,用户名不能为空");
        }

        // Token校验
        if (!tokenService.isUserIdEqualToken(username, token)) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "Token校验失败,请重新登录");
        }

        List<LineItemBO> lineItemBOList = orderService.getLineItemBOListByOrderId(orderId);
        List<LineItemVO> lineItemVOList = new ArrayList<>();
        for (LineItemBO lineItemBO : lineItemBOList) {
            LineItemVO lineItemVO = LineItemBO.toLineItemVO(lineItemBO);
            lineItemVOList.add(lineItemVO);
        }
        if (lineItemVOList.isEmpty()) {
            return CommonResponse.createForSuccessMsg("未查询到该订单所购买的商品");
        }
        return CommonResponse.createForSuccess(lineItemVOList);
    }

    /**
     * 根据订单号获取该订单(表单和包含的商品)
     *
     * @param token    token
     * @param orderId  订单号
     * @param username 用户名
     * @return CommonResponse OrderVO:表单和包含的商品
     * @author huangzhangyan
     * @date 2022/4/24 13:55
     */
    @RequestMapping(value = "/accounts/{username}/order/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResponse<OrderVO> getOrderVOByOrderId(
            @RequestHeader("Authorization") MyToken token,
            @PathVariable("orderId") int orderId,
            @PathVariable String username) {
        // 非空判断
        if (null == username || "".equals(username)) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数错误,用户名不能为空");
        }

        // Token校验
        if (!tokenService.isUserIdEqualToken(username, token)) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "Token校验失败,请重新登录");
        }

        return CommonResponse.createForSuccess(OrderBO.toOrderVO(orderService.getOrderBOById(orderId)));
    }
}
